import { WS_SEND_DATA } from '../middleware/ws'
import { formatValue } from '../../utils/dataUtils'
import { TRADE_DEAL_DETAIL_ACTION } from '../reducers/tradeDealDetailReducer'

/**
 * 订阅实时成交
 * @param contract
 * @returns {function(...[*]=)}
 */
export function subscribeDealDetail (contract) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '1',
            LocalNo: 3,
            TopicID: '2',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}`,
            ResumeNo: -200
          }
        }
      })
    }
  }
}

/**
 * 取消订阅成交详情
 * @param contract
 * @returns {function(...[*]=)}
 */
export function unsubscribeDealDetail (contract) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '2',
            LocalNo: 3,
            TopicID: '2',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}`,
            ResumeNo: -200
          }
        }
      })
    }
  }
}

let pollDealDetailEnabled = true

export function setPollDealDetailEnabled (enabled) {
  pollDealDetailEnabled = enabled
}

function pollDealDetail (dispatch, getState) {
  setTimeout(() => {
    if (pollDealDetailEnabled) {
      const dealDetail = getState().trade.dealDetail.get('dealDetail')
      dispatch({
        type: TRADE_DEAL_DETAIL_ACTION,
        data: {
          showDealDetail: dealDetail
        }
      })
      pollDealDetail(dispatch, getState)
    }
  }, 200)
}

export function getDealDetail () {
  setPollDealDetailEnabled(true)
  return (dispatch, getState) => {
    pollDealDetail(dispatch, getState)
  }
}
